const $ = layui.jquery;
const form=layui.form;
const layer=layui.layer;
const dropdown=layui.dropdown;
const tree=layui.tree;
$(()=> {
    if(error){
        layer.msg(error);
        return;
    }

    dropdown.render({
        elem:"[name=parentName]",
        content:"<div id='category-tree'></div>",
        id:"drop",
        ready(){//下拉后执行的操作
            const url = ctx + "/sys/api/v1/category";
            $.ajax({
                url,
                method: "get",
                success(resp) {
                    if (resp.success) {
                        let data = resp.data;//树数据
                        tree.render({
                            elem: '#category-tree',
                            id: 'category-tree',//给树定义一个编号
                            data: data,//数据提前获取
                            customName: {
                                id: 'id',
                                title: 'name',
                                children: 'children'
                            },
                            click: function (obj) {
                                let cat = obj.data;  //获取当前点击的节点数据
                                $("[name=parentId]").val(cat.id);
                                $("[name=parentName]").val(cat.name);
                                dropdown.close("drop");//选完之后关闭
                            }
                        });
                    }
                }
            })
        }
    })
    form.val("edit-form",category);
    if(parentCat){
        $("[name=parentId]").val(parentCat.id);
        $("[name=parentName]").val(parentCat.name);
    }

})
// 点击提交按钮后的异步提交操作
function doSubmit(cb) {
    if(error){
        layer.msg(error);
        return;
    }
    let pass = form.validate("#edit-form")//参数验证
    if (!pass) {
        return;
    }
    // 验证通过，向后台发请求
    const url = ctx + "/sys/api/v1/category";
    let formData = form.val("edit-form");//参数为过滤器
    formData.id = category.id;

    $.ajax({
        url,
        method: "put",
        data: formData,
        success(resp) {
            if (resp.success) {
                if (typeof cb === "function") {
                    cb(resp.success)
                }
            }
        }, error(resp) {
            let json = resp.responseJSON;
            let msg = json.msg || "修改类别异常";
            layer.msg(msg);
        }
    })

}